<template>
    <div class="login">
        <span
            class="iconfont icon-chacha cha"
            @click="back"
            ></span>
        <p>登录/注册</p>
        <i>注册即送2600元新人礼包</i>
        <input v-model="uname" placeholder="请输入用户名" type="text" v-focus>
        <input v-model="pwd" placeholder="请输入密码" type="password">
        <button @click="login">登录</button>
    </div>
</template>

<script>
import { Dialog, Form } from 'vant'
import { mapState, mapActions, mapMutations } from 'vuex'
import { instance2 } from '@/utils/http'
export default {
  data () {
    return {
      uname: '',
      pwd: ''
    }
  },
  methods: {
    ...mapMutations('publicShow', ['hide', 'show']),
    back () {
      this.$router.back()
    },
    login () {
      // 用户名正则，4到16位（字母，数字，下划线，减号）
      const uReg = /^[a-zA-Z0-9_-]{4,16}$/
      // 密码强度正则，最少6位，包括至少1个大写字母，1个小写字母，1个数字
      const pReg = /^(\w){6,20}$/
      if (!uReg.test(this.uname) || !pReg.test(this.pwd)) {
        Dialog({ message: '您输入的用户名或密码不合法' })
        return
      }
      if (!this.uname.trim() || !this.pwd.trim()) {
        alert('密码和用户名一定要输入')
        return
      }
      instance2.post('/api/login', {
        username: this.uname,
        password: this.pwd
      }).then(res => { // 现在这里的res就是在http里面返回的res.data
        // 将token保存到本地存储里面去
        localStorage.setItem('token', res.token)
        this.$router.replace('/index')
      }).catch(err => {
        alert(err)
      })
      // 测试用户 wusf 123456Wu
    }
  },
  mounted () {
    this.hide()
    this.$store.commit('hide')
  },
  destroyed () {
    this.show()
    this.$store.commit('show')
  }
}
</script>

<style lang="scss" scoped>
.login {
    display: flex;
    flex-direction: column;
    padding: .8rem .3rem 0 .3rem;
    line-height: 1;
    .cha {
        position: absolute;
        top: .14rem;
        right: .14rem;
        font-size: .3rem;
    }
    p {
        font-size: .19rem;
        color: #000;
    }
    i {
        margin-top: .12rem;
        margin-bottom: .18rem;
        font-size: .14rem;
    }
    input {
        height: .5rem;
        border: 0;
        margin-top: .15rem;
        text-indent: .12rem;
        border: .01rem solid #ddd;
    }
    input::-webkit-input-placeholder{
        color: #ddd;
    }

    button {
        height: .5rem;
        border: 0;
        margin-top: .8rem;
        font-size: .23rem;
        color: #fff;
        background: #ddd;
    }
}
</style>
